#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <stdlib.h>

#define SERPORT 8001

int main(int argc, char* argv[]){
    //创建一个套接字
    int lfd = socket(AF_INET, SOCK_STREAM, 0);
    if(lfd < 0){
        perror("socket error");
        exit(1);
    }
    //int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
    struct sockaddr_in seraddr, cliaddr;
    seraddr.sin_family = AF_INET;
    seraddr.sin_port = htons(SERPORT);
    //192.168.0.184  主机字节序的字符串
    seraddr.sin_addr.s_addr = INADDR_ANY;//网络字节序的整形 INADDR_ANY = 0
    //给套接字绑定了IP+port
    int bret = bind(lfd, (struct sockaddr *)&seraddr, sizeof(seraddr));
    if(bret < 0){
        perror("bind error");
        exit(1);
    }
    int lret = listen(lfd, 64);
    printf("listen is return\n");
    //int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
    socklen_t addrlen = sizeof(cliaddr);
    //从全连接队列取出一个连接，返回的值是和客户端通信的socket的文件描述符
    while(1){
        //accept 返回的条件：全连接队列不为空
        int cfd = accept(lfd, (struct sockaddr *)&cliaddr, &addrlen);
        if(cfd < 0){
            perror("accept error");
            exit(1);
        }
        printf("accept is return\n");
        int buf[1024];

        //回射
        //read 返回的条件：socket不为空
        int ret = read(cfd, buf, sizeof(buf));
        write(STDOUT_FILENO, buf, ret);
        write(cfd, buf, ret);
    }
    
    return 0;
}
